﻿Imports MvcMusicStoreVB.Models

Namespace Controllers
    <Authorize(Roles:="Administrator")>
    Public Class StoreManagerController
        Inherits System.Web.Mvc.Controller

        Private storeDB As MusicStoreEntities = New MusicStoreEntities

        '
        ' GET: /StoreManager

        Function Index() As ActionResult
            Dim albums = storeDB.Albums.
                Include("Genre").
                Include("Artist")

            Return View(albums)
        End Function


        '
        ' GET: /StoreManager/Create

        Function Create() As ActionResult
            PopulateViewBagWithGenresAndArtists()
            Dim album = New Album
            Return View(album)
        End Function

        '
        ' POST: /StoreManager/Create

        <HttpPost()> _
        Function Create(ByVal album As Album) As ActionResult
            If ModelState.IsValid Then
                'Save Album
                storeDB.Albums.Add(album)
                storeDB.SaveChanges()
                Return RedirectToAction("Index")
            Else
                PopulateViewBagWithGenresAndArtists()
                Return View(album)
            End If
        End Function

        '
        ' GET: /StoreManager/Edit/5

        Function Edit(ByVal id As Integer) As ActionResult

            PopulateViewBagWithGenresAndArtists()

            Dim album = storeDB.Albums.Find(id)

            Return View(album)
        End Function

        '
        ' POST: /StoreManager/Edit/5

        <HttpPost()> _
        Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
            Dim album = storeDB.Albums.Find(id)

            If TryUpdateModel(album) Then
                storeDB.SaveChanges()
                Return RedirectToAction("Index")
            Else
                PopulateViewBagWithGenresAndArtists()
                Return View(album)
            End If
        End Function

        '
        ' GET: /StoreManager/Delete/5

        Function Delete(ByVal id As Integer) As ActionResult
            Dim album = storeDB.Albums.Find(id)

            Return View(album)
        End Function

        '
        ' POST: /StoreManager/Delete/5

        <HttpPost()> _
        Function Delete(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
            Dim album = storeDB.Albums.Find(id)

            storeDB.Albums.Remove(album)
            storeDB.SaveChanges()
            Return View("Deleted")
        End Function

        Private Sub PopulateViewBagWithGenresAndArtists()
            ViewBag.Genres = From g In storeDB.Genres
                             Order By g.Name
            ViewBag.Artists = From a In storeDB.Artists
                              Order By a.Name
        End Sub

    End Class
End Namespace